package api

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
	"io"
	"math/rand"
	"mxshop-api/user-web/forms"
	"mxshop-api/user-web/global"

	"net/http"
	"strings"
	"time"
)

func GenerateSmsCode(width int) string {
	//生成width长度的短信验证码
	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder
	for i := 0; i < width; i++ {
		fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}

func SendSMS(ctx *gin.Context) {
	sendSmsForm := forms.SendSmsForm{}
	if err := ctx.ShouldBind(&sendSmsForm); err != nil {
		if errors.Is(err, io.EOF) {
			ctx.JSON(http.StatusBadRequest, gin.H{"msg": "请求体为空"})
			return
		}
		zap.S().Errorw("表单绑定失败", "err", err)
		HandlerValidatorError(ctx, err)
		return
	}
	code := GenerateSmsCode(5)
	zap.S().Infof("注册验证码:%s ", code)
	client := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", global.ServerConfig.RedisInfo.Host, global.ServerConfig.RedisInfo.Port),
	})
	key := fmt.Sprintf("smscode:%s", sendSmsForm.Mobile)
	// 保存到 Redis，并设置过期时间
	err := client.Set(ctx, key, code, time.Duration(global.ServerConfig.RedisInfo.Expire)*time.Second).Err()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "发送失败"})
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "发送成功",
	})
}
